package com.imooc.security.core.controller;


import com.imooc.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 校验码 控制层
 *
 * @author yuelinbo
 * @date 2019/2/28 14:43
 **/
@RestController
public class ValidateCodeController {

    public static String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    @Autowired
    private SecurityProperties securityProperties;

    //Spring session 工具类
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        BufferedImage image = createImageCode(new ServletWebRequest(request));

        //图片写入session中
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, image);

        ImageIO.write(image, "JPEG", response.getOutputStream());


    }

    /**
     * 生成图片验证码
     *
     * @param request
     * @return
     */
    private BufferedImage createImageCode(ServletWebRequest request) {


        /* 请求的参数》应用级配置文件参数 》 默认参数 */
        int width = ServletRequestUtils.getIntParameter(request.getRequest(),"width",securityProperties.getWidth());
        int height = ServletRequestUtils.getIntParameter(request.getRequest(),"width",securityProperties.getHeight());

        Random r = new Random();
        //1.创建一个bufferedimage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.绘制长方形
        Graphics g = image.getGraphics();
        g.setColor(new Color(233, 222, 220));
        g.fillRect(0, 0, width, height);
        //3.绘制干扰线
        for (int i = 0; i < 200; i++) {
            g.setColor(new Color(40 + r.nextInt(200), 40 + r.nextInt(200), 40 + r.nextInt(200)));
            int x = r.nextInt(50);
            int y = r.nextInt(20);
            g.drawLine(x, y, x + r.nextInt(20), y + r.nextInt(15));
        }
        //4.写四位数字
        g.setColor(new Color(23, 22, 20));
        int checkCode = r.nextInt(9000) + 1000;
        g.drawString(checkCode + "", 15, 15);
        //关闭Graphics对象，释放资源
        g.dispose();

        return image;
    }


}
